package com.salemanagement.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.salemanagement.mapper.UserBalanceLogMapper;
import com.salemanagement.mapper.UserBalanceMapper;
import com.salemanagement.mapper.UserDetailMapper;
import com.salemanagement.mapper.VipMapper;
import com.salemanagement.service.VipService;
import com.salemanagement.utils.HttpClient;
import com.salemanagement.vo.RechargeVo;
import com.salemanagement.vo.payResultVo;
import com.three.core.entity.UserBalanceLog;
import com.three.core.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class VipServiceImpl implements VipService {
    @Autowired
    private VipMapper vipMapper;
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    @Autowired
    private UserBalanceLogMapper userBalanceLogMapper;
    
    private static final String APP_ID = "wx8087d8149331d27c";
    private static final String MCH_ID = "1532192611";
    private static final String KEY = "Cc158380629071583806290715838062";
    private static final String NOTIFY_URL = "http://www.baidu.com";
    
    @Override
    public R getRechargeNative(RechargeVo rechargeVo) {
        try {
            // 统一下单接口
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            Map<String, String> data = new HashMap<>();
            data.put("appid", APP_ID);
            data.put("mch_id", MCH_ID);
            data.put("nonce_str", WXPayUtil.generateNonceStr());
            data.put("body", "会员充值");
            data.put("out_trade_no", rechargeVo.getDetailId());
            data.put("total_fee", "1");
            data.put("spbill_create_ip", "127.0.0.1");
            data.put("notify_url", NOTIFY_URL);
            data.put("trade_type", "NATIVE");
            
            // 签名
            String sign = WXPayUtil.generateSignature(data, KEY);
            data.put("sign", sign);
            
            // 发送请求
            HttpClient client = new HttpClient(url);
            client.setXmlParam(WXPayUtil.mapToXml(data));
            client.post();
            
            // 获取返回结果
            String result = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            
            if ("SUCCESS".equals(resultMap.get("return_code"))) {
                payResultVo payResult = new payResultVo();
                payResult.setCodeUrl(resultMap.get("code_url"));
                payResult.setPrice(rechargeVo.getRechargeMoney());
                payResult.setOrderNo(rechargeVo.getDetailId());
                return new R<>(200, "获取支付二维码成功", payResult);
            } else {
                return new R<>(500, resultMap.get("return_msg"), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(500, "系统错误", null);
        }
    }
    
    @Override
    public R queryPayStatus(RechargeVo rechargeVo) {
        try {
            String url = "https://api.mch.weixin.qq.com/pay/orderquery";
            Map<String, String> data = new HashMap<>();
            data.put("appid", APP_ID);
            data.put("mch_id", MCH_ID);
            data.put("out_trade_no", rechargeVo.getDetailId());
            data.put("nonce_str", WXPayUtil.generateNonceStr());
            
            // 签名
            String sign = WXPayUtil.generateSignature(data, KEY);
            data.put("sign", sign);
            
            // 发送请求
            HttpClient client = new HttpClient(url);
            client.setXmlParam(WXPayUtil.mapToXml(data));
            client.post();
            
            // 获取返回结果
            String result = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            
            if ("SUCCESS".equals(resultMap.get("return_code"))) {
                if ("SUCCESS".equals(resultMap.get("trade_state"))) {
                    int i = userBalanceMapper.updateBalance(rechargeVo.getUserId(),rechargeVo.getAccountMoney(),rechargeVo.getStoreId());
                    UserBalanceLog userBalanceLog = new UserBalanceLog();
                    userBalanceLog.setUserId(Math.toIntExact(rechargeVo.getUserId()));
                    userBalanceLog.setStoreId(Math.toIntExact(rechargeVo.getStoreId()));
                    userBalanceLog.setRechargeMoney(rechargeVo.getRechargeMoney());
                    userBalanceLog.setDiscountsMoney(rechargeVo.getDiscountsMoney());
                    userBalanceLog.setAccountMoney(rechargeVo.getAccountMoney());
                    userBalanceLog.setRechargeTime(LocalDateTime.now());
                    int i1 = userBalanceLogMapper.insertBalanceLog(userBalanceLog);
                    return new R<>(200, "支付成功", null);
                } else if ("NOTPAY".equals(resultMap.get("trade_state"))) {
                    return new R<>(501, "未支付", null);
                } else {
                    return new R<>(500, resultMap.get("trade_state_desc"), null);
                }
            } else {
                return new R<>(500, resultMap.get("return_msg"), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(500, "系统错误", null);
        }
    }
} 